package com.tanchengjin.admin.modules.blog.service.impl;

import com.tanchengjin.admin.modules.blog.controller.pojo.Category;
import com.tanchengjin.admin.modules.blog.service.CategoryService;
import com.tanchengjin.admin.modules.cms.mapper.CategoryMapper;
import com.tanchengjin.admin.modules.cms.pojo.ArticleCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public ArticleCategory findByBy(Long id) {
        return null;
    }

    @Override
    public List<ArticleCategory> getAll() {
        List<ArticleCategory> all = categoryMapper.getAll();
        return all;
    }


    @Override
    public int delete(Long[] id) {
        return 0;
    }

    @Override
    public int update(ArticleCategory category) {
        return 0;
    }

    @Override
    public List<ArticleCategory> getTree() {
        List<ArticleCategory> categories = handlerTree(new ArrayList<>());
        return categories;
    }

    private List<ArticleCategory> handlerTree(List<ArticleCategory> categoryList) {
        if (categoryList == null || categoryList.size() <= 0) {
            categoryList = categoryMapper.getAllAndParentIdIsNull();
        }
        for (ArticleCategory category : categoryList) {
            List<ArticleCategory> children = categoryMapper.selectByParentId(category.getId());
            if (children != null && children.size() >= 1) {
                category.setChildren(children);
                this.handlerTree(children);
            }
        }
        return categoryList;
    }
}
